package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.constant.OrderConstant;
import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;
import com.atguigu.springcloud.lb.ILoadBalancer;
import lombok.AllArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * @author : wenchao.long
 * @date : Created in 2020/12/10 17:10 周四
 * @description :
 */
@RestController
@AllArgsConstructor
@RequestMapping("/consumer")
public class OrderController {

    private final RestTemplate restTemplate;

    private final ILoadBalancer loadBalancer;

    private final DiscoveryClient discoveryClient;

    @GetMapping("/payment/zipkin")
    public String paymentZipkin() {
        return restTemplate.getForObject("http://localhost:8001" + "/payment/zipkin", String.class);
    }

    @GetMapping("/payment/lb")
    public String getLoadBalancer() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() == 0) {
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        return restTemplate.postForObject(OrderConstant.PAYMENT_URL + "/payment/save", payment, CommonResult.class);
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(OrderConstant.PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

}
